package com.doupi.partner.manager.gateway;

import com.doupi.partner.util.RedisUtils;
import com.doupi.partner.util.RegexUtils;
import com.doupi.partner.util.RuntimeBusinessException;
import com.doupi.partner.util.constant.UtilConstants;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.net.URLEncoder;

/**
 * 短信服务实现
 * 
 * @author Super Jens Wang
 *
 * @version 1.0 @ 2016年9月28日 下午11:19:35
 */
@Service
public class SmsManager {
	private final static Logger LOGGER = LoggerFactory.getLogger(SmsManager.class);

	@Value("#{doupi_partner_util_config.sms_url}")
	private String smsUrl;

	@Value("#{doupi_partner_util_config.sms_name}")
	private String smsName;

	@Value("#{doupi_partner_util_config.sms_pwd}")
	private String smsPwd;

	@Value("#{doupi_partner_util_config.sms_sign}")
	private String sign;

	@Value("#{doupi_partner_util_config.sms_count_limit}")
	private Integer smsCountLimit;

	private final RedisUtils redisUtils;

	@Autowired
	public SmsManager(RedisUtils redisUtils) {
		this.redisUtils = redisUtils;
	}

	public boolean sendSMS(String mobile, String content) {
		boolean flag = false;
		String countString = redisUtils.get(UtilConstants.MOBILE_SMS_SEND_COUNT + mobile);
		int count = 0;
		if (StringUtils.isNotBlank(countString) && RegexUtils.isNumber(countString)) {
			count = Integer.parseInt(countString);
		}
		if (count > smsCountLimit) {
			throw RuntimeBusinessException.createException("短信发送太频换，24小时后再来");
		}
		try {
			// 创建StringBuffer对象用来操作字符串
			String urlString = smsUrl + "?" + "name=" + smsName + "&pwd=" + smsPwd + "&mobile=" + mobile + "&content=" + URLEncoder.encode(content, System.getProperty("file.encoding")) + "&stime="
					+ "&sign=" + URLEncoder.encode(sign, System.getProperty("file.encoding")) + "&type=pt&extno=";
			LOGGER.info("[smsSend] -- 发送短信地址：{}", urlString);
			URL url = new URL(urlString);
			// 返回结果为‘0，20140009090990,1，提交成功’ 发送成功 具体见说明文档
			String returnStr = IOUtils.toString(url);

			LOGGER.info("[smsSend] -- 发送短信响应信息为：{}, {}", mobile, returnStr);

			// 返回发送结果
			if (returnStr.contains("提交成功")) {
				flag = true;
				redisUtils.setex(UtilConstants.MOBILE_SMS_SEND_COUNT + mobile, String.valueOf(++count), 24 * 60 * 60);
			}
		} catch (Throwable e) {
			LOGGER.error("发送短信失败", e);
		}
		return flag;
	}
}
